<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Carbon\CarbonInterface;

class OrderNumberGenerator
{
    /**
     * 生成订单号：YYYYMMDD + 6位自增序号
     * 可选传入日期用于历史数据（如 Seeder）
     */
    public function generate(?CarbonInterface $date = null): string
    {
        $dateKey = ($date ?? now())->format('Ymd');

        // 使用数据库事务保证并发安全
        $sequence = DB::transaction(function () use ($dateKey) {
            $row = DB::table('order_sequences')->where('date', $dateKey)->lockForUpdate()->first();

            if (!$row) {
                DB::table('order_sequences')->insert([
                    'date' => $dateKey,
                    'seq' => 1,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
                return 1;
            }

            $newSeq = ($row->seq ?? 0) + 1;
            DB::table('order_sequences')
                ->where('id', $row->id)
                ->update([
                    'seq' => $newSeq,
                    'updated_at' => now(),
                ]);

            return $newSeq;
        });

        $seqString = str_pad((string) $sequence, 6, '0', STR_PAD_LEFT);
        return $dateKey . $seqString;
    }
}


